﻿Ext.BLANK_IMAGE_URL = '../ext2/resources/images/default/s.gif';
		Ext.lib.Ajax.defaultPostHeader += '; charset=UTF-8';		
		Ext.QuickTips.init();
		
		var about_id,reqUrl,mark,_back;
		var priarti_reader =  new Ext.data.JsonReader({
			     totalProperty: "results",
			     root:"items",
			     fields : [
			           {name: 'id'},            {name: 'title'},
				       {name: 'content'},       {name: 'author'},
                       {name: 'goodVote'},      {name: 'badVote'},
				       {name: 'artiSrc'},       {name: 'total'},
				       {name: 'datatime'}	
			         ]
		});
		
		//数据代理
		var priarti_proxy = new Ext.data.HttpProxy({
			   url : '../admin/arti/action/Com_prigetArtiList.do'	 
        }); 
        
		//数据仓库
        var arti_groupingStore = new Ext.data.GroupingStore({
			   groupOnSort:false,                                    //分组时不重新排序
			   proxy : priarti_proxy,   reader: priarti_reader              
        });  
        
        arti_groupingStore.on("beforeload", function(thiz, options) {
				 	       thiz.baseParams=_params;
		        	});
       var priarti_toolbar = new Ext.PagingToolbar({ // 分页工具栏

			store : arti_groupingStore,
			pageSize : limit,
			displayInfo : true,
			displayMsg : '第 {0} 条到 {1} 条，一共 {2} 条',
			emptyMsg : "没有记录",
			items : [{
						enableToggle : true,
						text : '发布',
						cls : 'x-btn-text-icon details',
						icon : "../ext2/images/add.gif",
						toggleHandler : arti_addInfo
					},
                   { 	enableToggle: true,
	                    text: '批量删除',    
	                    cls: 'x-btn-text-icon details',icon:"../ext2/images/delete.gif",
	                    toggleHandler: arti_deletemore
                   },
                   { 	enableToggle: true,
	                    text: '文章搜索',    
	                    cls: 'x-btn-text-icon details',icon:"../ext2/images/preview.gif",
	                    toggleHandler: arti_serch
                   }]
		});
		
		
		 var priarti_cb = new Ext.grid.CheckboxSelectionModel();	
		//创建Grid表格组件
		var article_grid =Ext.extend(Ext.grid.GridPanel,{
			//applyTo : 'imformation',
			id:'article_grid',
			closable:true,
			title:'信息发布',
			frame:true,
			width:document.body.clientWidth-190,
			height:document.body.clientHeight-87,
			stripeRows:true,
			loadMask:true,
		    tbar : priarti_toolbar,
		    sm:priarti_cb,
			store: arti_groupingStore,
			//设置表格分组视图
			view : new Ext.grid.GroupingView({
				groupTextTpl : '{text}(共{[values.rs.length]}条)',  //定义分组行模板


				groupByText : '使用当前字段进行分组',                  //表头菜单提示信息
				showGroupsText : '表格分组',                         //表头菜单提示信息
				showGroupName : true,                              //显示分组字段名称
				startCollapsed : false,                            //展开分组
				hideGroupedColumn : false                          //隐藏分组列


			}),
			columns: [                                             //配置表格列
			         new Ext.grid.RowNumberer({
					       header : '行号',
					       width : 40
				     }),                                            //表格行号组件
				priarti_cb,
				{header: "编号", width: 60, dataIndex: 'id', sortable: true},
			    {header: "标题", width: 235, dataIndex: 'title', sortable: true},
			    {header: "文章来源", width: 140, dataIndex: 'artiSrc', sortable: true},
			    {header: "作者", width: 80, dataIndex: 'author', sortable: true},
			    {header: "鲜花", width: 190, dataIndex: 'goodVote', sortable: true},
			    {header: "鸡蛋", width: 70, dataIndex: 'badVote', sortable: true},
			    {header: "点击率", width: 70, dataIndex: 'badVote', sortable: true},
			    {header: "发布时间", width: 140, dataIndex: 'datatime', sortable: true},
			    {header: "功能操作", width: 100, dataIndex: 'id', renderer:renderUrl}
			]
		});
		
		function renderUrl(value){		    
		    var strurl = "<a target='_blank' href='/front/arti/action/Com_getPriArti.do?id="+value+"&resPath=%2FfrontJsp%2FcontentView.jsp'><img img style='margin-left: 6px;' src='../ext2/images/select1.png' title='预览' /></a>" +
		            "<a href='javascript:arti_update(\""+value+"\")'><img style='margin-left: 6px;'  src='../ext2/images/edit.png' title='修改文章'  /></a>" +
		    		"<a href='javascript:arti_aboutArti(\""+value+"\")'><img style='margin-left: 6px;'  src='../ext2/images/add.gif' title='添加相关文章' /></a>" +
		    		"<a href='javascript:arti_delete(\""+value+"\")'><img style='margin-left: 6px;'  src='../ext2/images/delAll.gif' title='删除文章' /></a>";		   
		    return strurl;
		}
		
		//定义一人from表单对象
		var arti_infoForm ;
	    function newArtiFrom(){
	      arti_infoForm = new Ext.FormPanel({
				labelSeparator : "：",
				frame:true,
				border:false,
				fileUpload:true,
				labelAlign:'right',
				items : [ 
				{
		            xtype:'tabpanel',
		            baseCls:'x-plain',
		            plain:true,
		            activeTab: 0,
		            height:750,
		            layoutOnTabChange:true,
		            deferredRender:false,
		            items:[{
		                title:'基本信息',
		                layout:'form',
		                items: [
		                 		{xtype:"textfield",fieldLabel:"所属栏目",name:"artiType",width:200,readOnly:true, value:arti_chanl_name},
					            {xtype:'textfield', name:'title', fieldLabel:'标题', width:590,
					             allowBlank:false,blankText:'请输入标题', maxLength:180,maxLengthText:'您输入的标题字符太长！不能超过180个字符'},
							    {
							    layout:'column',
					            items:[
					                    {
					            	         columnWidth:.5,layout: 'form',            	        
					                         items: [{xtype:'textfield', name:'artiSrc',value:'无', fieldLabel:'来源',maxLength:60,maxLengthText:'字符太长', width:170,allowBlank:false,blankText:'请输入来源'}]
					                     },
					                     {
					                         columnWidth:.5,layout: 'form',
					                         items:[{xtype:'textfield',name:'author',fieldLabel:'原文作者',value:'侠名',maxLength:6,maxLengthText:'字符太长',blankText:'请输入原文作者',allowBlank:false,width:160}]
					                     }
								   ]},
								   
								   	{layout:'column',
							            items:[
							             {
							            	         columnWidth:.5,layout: 'form',	        
							                         items: [{xtype:'textfield',id:'image',name:'image',autoScroll:false, fieldLabel:'选择标题图片',
								                         autoCreate : {   
												            tag : "input",
												            type : "file",
												            size:"30"
												        }
											        }]
							                     }
										]},{xtype: 'label', text: '标题图片预览：', width:'110',style:'margin-bottom:30px;'},
										{  
										    xtype: 'box', //或者xtype: 'component
										    width: 320, //图片宽度
										    height: 260, //图片高度
										    id:'titleImgs',
										    autoEl: {  
								                tag: 'input',      
								                type: 'image', 	                
								                style:'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);' ,    
								                name: 'titleImgs', 	                
										        src: '/admin/img/notimage.jpg'    //指定url路径 默认显示图片 
										    } 
										} 
				   	]},{
		                title:'文章内容',
		                layout:'form',
		                labelWidth:60,
		                items: [
		               		{xtype:'fckeditor', name:'content',fieldLabel:'内容', width:480, height:380,allowBlank:false,blankText:'内容不允许为空'}
						
	        			]
		            }	            
		            ]
		        },			
	           	{xtype:'hidden', name:'aritId', fieldLabel:'aritId',value:about_id},
	           	{xtype:'hidden', name:'typeId', fieldLabel:'typeId',value:type_id},
				{xtype:'hidden', name:'id', fieldLabel:'id'}
				],	
				buttons:[
					{
						text : '关闭',
						handler : function(){
						    arti_win.close();
						}			
					},{
						text : '保存',
						handler :  arti_submitForm
					}
				]
			});	
			

			var img_reg=/\.([jJ][pP][gG]){1}$|\.([jJ][pP][eE][gG]){1}$|\.([gG][iI][fF]){1}$|\.([pP][nN][gG]){1}$|\.([bB][mM][pP]){1}$/ 
			
			arti_infoForm.on('render',function(f){      
	        arti_infoForm.form.findField('image').on('render',function(){      
	            Ext.get('image').on('change',function(field,newValue,oldValue ){      
		            var url
	               url = 'file:///'+Ext.get('image').dom.value;    
		           if(img_reg.test(url)){      
		                           if(Ext.isIE){      
		        							var image = Ext.get('titleImgs').dom;      
											image.src = Ext.BLANK_IMAGE_URL;//覆盖原来的图片      
											image.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src= url;      
		                                }else{      
		                                      Ext.get('titleImgs').dom.src = Ext.get('image').dom.files.item(0).getAsDataURL();      
		                                }      
		                            }  
	                            },this);  
	        },this);      
	    },this);  
	    	
	    }
    	var arti_win ;
	     //创建弹出窗口 
	    function newArtiWindow(){
	    	newArtiFrom();
		    arti_win = new Ext.Window({
				layout:'fit',
				collapsible : true,  
			    width:760,
			    height:500,
			    closeAction:'close',   
				resizable : false,
				shadow : true,
			    closable:true,
			    bodyStyle:'padding:5 5 5 5',
			    animCollapse:true,
			    modal: true,		    
			    autoDestroy:true,
				items:[arti_infoForm]
			}); 
	    }
	    
	    //搜索表单
	    var arti_searchForm = new Ext.FormPanel({
			labelSeparator : "：",
			frame:true,
			border:false,
			fileUpload:true,
			buttonAlign:'center',
			baseCls:'y-plain',
			labelWidth:40,
			labelAlign:'right',
			items : [ 
			{defaults:{width:310},layout:'form',	baseCls:'y-plain',
			 items:[
			     {xtype:'textfield', name:'title', fieldLabel:'标题', 
                 allowBlank:true,blankText:'请输入标题', maxLength:180,maxLengthText:'您输入的标题字符太长！不能超过180个字符'}
			 ]
			},	
			{
		    layout:'column',	baseCls:'y-plain',
            items:[
            	     {
            	         columnWidth:.45,layout: 'form',baseCls:'y-plain',      	        
                         items: [{xtype:'datefield', name:'begin', fieldLabel:'日期',format:'Y-m-d',width:130,blankText:'请输入查找的发布时间!'}]
                     },
                     { 
            	         columnWidth:.45,layout: 'form',	baseCls:'y-plain',
                         items: [{xtype:'datefield', name:'end', fieldLabel:'到',format:'Y-m-d',width:130,blankText:'请输入查找的发布时间!'}]
                     }
			   ]
			},        
		    {xtype:'hidden', name:'id', fieldLabel:'id'}
			],	
			buttons:[
				{
					text : '关闭',
					handler : function(){
					    arti_searchwin.hide();
					}				
				},{
					text : '搜索',
					handler :  arti_searchFormSub
				}
			]
		});
	    
	    //创建搜索弹出窗口 
		var arti_searchwin = new Ext.Window({
			layout:'fit',
		    width:425,
		    height:150,
		    closeAction:'hide',		    
			resizable : false,
			shadow : true,
			plain:true,
		    closable:true,
		    bodyStyle:'padding:5',
		    animCollapse:true,
		    modal: true,		    
		    autoDestroy:false,
			items:[arti_searchForm]
		});
		
				//提交表单数据
		function arti_searchFormSub(){		
			var titles = arti_searchForm.form.findField('title').getValue();
			var begindates = arti_searchForm.form.findField('begin').getValue();	
			var enddates =  arti_searchForm.form.findField('end').getValue();
			var begindatefmt="";
			var enddatefmt="";
			if(begindates != null && begindates != "")
				begindatefmt = begindates.dateFormat('Y-m-d');
			if(enddates != null && enddates != "")
				enddatefmt = enddates.dateFormat('Y-m-d');
			var arti_grid_store;
			arti_searchwin.hide();
			if(mark==0){
				arti_grid_store=arti_groupingStore;
			}else{
				arti_grid_store=about_groupingStore;
			}
			_params={start:0,limit:limit,title:titles,artiType:arti_chanl_name,aritId:about_id,begin:begindates,end:enddatefmt};
			arti_grid_store.load({	   
			callback : function(r, options, success) {
				if (success == false) {
		            Ext.Msg.alert("错误", "加载数据出错.");
				}
	        }
       		});		
		} 
	    
		//文章搜索
		function arti_serch(){
			mark = 0;
			arti_searchForm.form.reset();
			arti_searchwin.setTitle("搜索文章");
			arti_searchwin.show();	
		}
		
		function arti_addInfo(){
			mark = 0;
			_params={artiType:arti_chanl_name,start : 0,limit :limit};
			reqUrl = '../admin/arti/action/Com_priartiSave.do';
			setWindonMsg(true,"发布新信息");
		}
		
		//修改数据
		 function arti_update(infoId){
			setWindonMsg(false,"修改新闻信息");
			mark = 0;
			reqUrl = '../admin/arti/action/Com_priartiUpdate.do';
			arti_req_update(infoId,'../admin/arti/action/Com_prigetArtiById.do');
		}
		
		function arti_req_update(id,url){
			arti_infoForm.form.load({
				waitMsg : '正在加载数据请稍后...',                        //提示信息
				waitTitle : '提示',                                    //标题
				url : url,	                                          //请求的url地址
				params : {id:id},
				method:'POST',                                        //请求方式
				success:function(form,action){                        //加载成功的处理函数					
					var titleImgsobj = Ext.getCmp('titleImgs');
					var img = action.result.data.titleImg;
					if(img){
						titleImgsobj.getEl().dom.src = img;		
					}
				},
				failure:function(form,action){                        //加载失败的处理函数
                   	failure(action);
				}
			});
		}
		
		//批量删除
		function arti_deletemore(){
			var ids = getInfoIds("article_grid");
			Ext.MessageBox.confirm("提示","确定要将这 "+ids.length+" 篇文章全部删除吗？",function(btnId)
				{
					if(btnId == 'yes')
					{
						var id = ids;
						arti_delete(id);
					}
				});
		}
		
		//删除数据
		function arti_delete(id){
			mark = 0;
			arti_req_delete(id,'../admin/arti/action/Com_priartiDelete.do');
		}
		
		function arti_req_delete(id,url){
			var msgTip = Ext.MessageBox.show({
				title:'Tips',
				width : 250,
				msg:'正在删信息,请稍后......'
			});
			Ext.Ajax.request({
				url : url,
				params : {ids : id},
				method : 'POST',
				success : function(response,options){
					msgTip.hide();
					if(mark == 0){
			         	 arti_groupingStore.reload();
			         }else{
			         	 about_groupingStore.reload();
			         }
				},
				failure : function(response,options){
					msgTip.hide();
					var result = Ext.util.JSON.decode(response.responseText);
				    Ext.Msg.alert('提示',result.msg);
				}
			});		
		}
		
		//提交表单数据
		function arti_submitForm(){
			//判断当前执行的提交操作，isAdd为true表示执行新增操作，false表示执行修改操作
			if(arti_infoForm.isAdd){				
				arti_infoForm.form.submit({
					clientValidation:true,                   　　　　　　　　 //进行客户端验证
					waitMsg : '正在提交数据请稍后',              　　　　　　　 //提示信息
					waitTitle : '提示',                                  //标题
					url : reqUrl,                                     	//请求的url地址
					method:'POST',        
					enctype:'multipart/form-data',
					success:function(form,action){                      //加载成功的处理函数
						success(action);
					},
					failure:function(form,action){                      //加载失败的处理函数
						failure(action);
					}
				});
			}else{				
				    arti_infoForm.form.submit({
					clientValidation:true,                              //进行客户端验证
					waitMsg : '正在提交数据请稍后',                       　　 //提示信息
					waitTitle : '提示',                                 　　  //标题
					url : reqUrl, //请求的url地址
					method:'POST',                                      //请求方式
					enctype:'multipart/form-data',
					success:function(form,action){                      //加载成功的处理函数
						success(action);
					},
					failure:function(form,action){                　　　　　//加载失败的处理函数
						failure(action);
					}
				});
			}
		}  
		
		//获取选中数据的id
		function getInfoIds(grid_name){
			var recs;
			if(grid_name){
				 recs = Ext.getCmp(grid_name).getSelectionModel().getSelections();
			}else{
				recs = about_grid.getSelectionModel().getSelections();
			}
			
			var list = [];
			if(recs.length == 0){
				Ext.Msg.alert('提示','请选择要进行操作的数据！');
				return;
			}else{
				for(var i = 0 ; i < recs.length ; i++){
					var rec = recs[i];
					list.push(rec.get('id'));
				}
			}
			return list;
		}
		
		//请求失败后调用方法
		function failure(action){
			 var result =action.result;
			 Ext.Msg.alert('提示',result.msg);
		}
		
		//请求成功后调用处理方法
		function success(action){
	         arti_win.close();			
	         if(mark == 0){
	         	 arti_groupingStore.reload();
	         }else{
	         	 about_groupingStore.reload();
	         }
		}
		
		//窗口信息设置方法
		function setWindonMsg(bool,msg){
			newArtiWindow();
			arti_infoForm.isAdd = bool;
			arti_win.setTitle(msg);
			arti_win.show();
		}
		
		function arti_aboutArti(aboutId){
			about_groupingStore.baseParams={start:0,limit:limit};
			_back = _params;                                   //参数备份，用于窗口隐藏后数据还原
			_params = {aritId:aboutId,start:0,limit:limit};
			about_id = aboutId;
			about_groupingStore.load();
			arti_gridwin.show();
		}
		
		//--------------------------------------------------------------------------------------------------------------------------------------------------
		
		function aboutRend(value){		    
		    var strurl = "<a target='_blank' href='/front/arti/action/Com_getPriArti.do?id="+value+"&resPath=%2FfrontJsp%2FcontentView.jsp'><img img style='margin-left: 6px;' src='../ext2/images/select1.png' title='预览' /></a>" +
		            "<a href='javascript:about_update(\""+value+"\")'><img style='margin-left: 6px;'  src='../ext2/images/edit.png' title='修改文章'  /></a>" +
		    		"<a href='javascript:about_delete(\""+value+"\")'><img style='margin-left: 6px;'  src='../ext2/images/delAll.gif' title='删除文章' /></a>";		   
		    return strurl;
		}
		
		//数据代理
		var about_proxy = new Ext.data.HttpProxy({
			   url : '../admin/arti/action/Com_forgetArtiList.do'	 
        }); 
        
		//数据仓库
        var about_groupingStore = new Ext.data.GroupingStore({
        	　  baseParams:{aritId:about_id,start : 0,limit :limit},
			   groupOnSort:false,                                    //分组时不重新排序
			   proxy : about_proxy,   reader: priarti_reader              
        });  
        
	   about_groupingStore.on("beforeload", function(thiz, options) {
				 	       thiz.baseParams=_params;
		        	});
		        	
		 var about_toolbar = new Ext.PagingToolbar({ // 分页工具栏

			store : about_groupingStore,
			pageSize : limit,
			displayInfo : true,
			displayMsg : '第 {0} 条到 {1} 条，一共 {2} 条',
			emptyMsg : "没有记录",
			items : [{
						enableToggle : true,
						text : '发布',
						cls : 'x-btn-text-icon details',
						icon : "../ext2/images/add.gif",
						toggleHandler : about_addInfo
					},
                   { 	enableToggle: true,
	                    text: '批量删除',    
	                    cls: 'x-btn-text-icon details',icon:"../ext2/images/delete.gif",
	                    toggleHandler: about_deletemore
                   },{ 	enableToggle: true,
	                    text: '文章搜索',    
	                    cls: 'x-btn-text-icon details',icon:"../ext2/images/preview.gif",
	                    toggleHandler: about_serch
                   }]
		});
		
		
		   var about_grid = new Ext.grid.GridPanel({
		   	id:about_grid,
			frame:true,
			width:document.body.clientWidth-190,
			height:document.body.clientHeight-137,
			stripeRows:true,
			loadMask:true,
		    tbar : about_toolbar,
		    sm:priarti_cb,
			store: about_groupingStore,
			//设置表格分组视图
			view : new Ext.grid.GroupingView({
				groupTextTpl : '{text}(共{[values.rs.length]}条)',  //定义分组行模板


				groupByText : '使用当前字段进行分组',                  //表头菜单提示信息
				showGroupsText : '表格分组',                         //表头菜单提示信息
				showGroupName : true,                              //显示分组字段名称
				startCollapsed : false,                            //展开分组
				hideGroupedColumn : false                          //隐藏分组列


			}),
			columns: [                                             //配置表格列


			         new Ext.grid.RowNumberer({
					       header : '行号',
					       width : 40
				     }),                                            //表格行号组件
				priarti_cb,
				{header: "编号", width: 40, dataIndex: 'id', sortable: true},
			    {header: "标题", width: 195, dataIndex: 'title', sortable: true},
			    {header: "发布时间", width: 145, dataIndex: 'issueDate', sortable: true},
			    {header: "文章来源", width: 110, dataIndex: 'artiSrc', sortable: true},
			    {header: "作者", width: 80, dataIndex: 'author', sortable: true},
			    {header: "点击数", width: 60, dataIndex: 'pv', sortable: true},
			    {header: "ip量", width: 50, dataIndex: 'ip', sortable: true},
			    {header: "功能操作", width: 100, dataIndex: 'id', renderer:aboutRend}
			]
		});
	    
		
	    //相关新闻弹出窗
	    var arti_gridwin = new Ext.Window({
				layout:'fit',
				collapsible : true,  
			    width:880,
			    height:530,
			    closeAction:'hide',   
				resizable : false,
				shadow : true,
			    closable:true,
			    bodyStyle:'padding:5 5 5 5',
			    animCollapse:true,
			    modal: true,		    
			    autoDestroy:false,
				items:[about_grid],
			    listeners: { 
			     	hide: function(){
			     		_params=_back;
			     	}
			    }
			}); 
		
			 
		function about_addInfo(){
			mark = 1;
			_params={start:0,limit:limit,aritId:about_id};
			reqUrl = '../admin/arti/action/Com_forartiSave.do';
			setWindonMsg(true,"相关新闻信息");
		}
		
		//相关文章搜索
		//文章搜索	
		function about_serch(){
			mark = 1;
			arti_searchForm.form.reset();
			arti_searchwin.setTitle("搜索文章");
			arti_searchwin.show();	
		}
		
		//批量删除
		function about_deletemore(){
			var ids = getInfoIds();
				Ext.MessageBox.confirm("提示","确定要将这 "+ids.length+" 篇文章全部删除吗？",function(btnId)
				{
					if(btnId == 'yes')
					{
						var id = ids;
						about_delete(id);
					}
				});
		}	
		
		//修改数据
		function about_update(infoId){
			setWindonMsg(false,"修改相关新闻信息");
			mark = 1;
			reqUrl = '../admin/arti/action/Com_forartiUpdate.do';
			arti_req_update(infoId,'../admin/arti/action/Com_forgetArtiById.do');
		}
		
		//删除数据
		function about_delete(id){
			mark = 1;
			arti_req_delete(id,'../admin/arti/action/Com_forartiDelete.do');
		}	
		
		Ext.Window.prototype.beforeDestroy = function(){   
        Ext.destroy(     
    		this.focusEl,  // 新增   
    		this.bwrap,    // 新增     
            this.resizer,   
            this.dd,   
            this.proxy,   
            this.mask   
        );   
        Ext.Window.superclass.beforeDestroy.call(this);   
       
	   this.focusEl=null;  // 新增   
	   this.bwrap=null;    // 新增  
	}